package com.hhp.hhptt.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhp.hhptt.entity.Dic;
import com.hhp.hhptt.entity.Menu;
import com.hhp.hhptt.mapper.DicMapper;
import com.hhp.hhptt.service.IDicService;
import com.hhp.hhptt.service.IMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hhp
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

private static Logger logger  = LoggerFactory.getLogger(MenuController.class);

@Resource
private IMenuService menuService;

@Autowired
IDicService dicService;

@Resource
private DicMapper dicMapper;


@PostMapping("/save")
public Boolean save(@RequestBody Menu menu) {
        logger.info("menu==="+menu);
        return menuService.saveOrUpdate(menu);
        }

@DeleteMapping("/delete/{id}")
public Boolean delete(@PathVariable Integer id) {
        return menuService.removeById(id);
        }
@PostMapping("/deleteBatch")
public Boolean deleteBatch(@RequestBody List<Integer> ids) {
        return menuService.removeByIds(ids);
        }



@GetMapping("/getAll")
public List<Menu> findAll(@RequestParam String name) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if(!"".equals(name)){
                queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");
        List<Menu> list = menuService.list(queryWrapper);
        //pid 为null的一级菜单
        List<Menu> parentNode = list.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList());
        for(Menu menu:parentNode){
                //一级菜单的子菜单
                menu.setChildren(list.stream().filter(m -> menu.getId().equals(m.getPid())).collect(Collectors.toList()));
        }

        return parentNode;
        }
@GetMapping("/{id}")
public Menu findOne(@PathVariable Integer id) {
        return menuService.getById(id);
        }

@GetMapping("/icons")
public List<Dic> getIcons(){
        QueryWrapper<Dic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type","icon");
        List<Dic> list = dicService.list(queryWrapper);

    return list;
}
@GetMapping("/page")
public Page<Menu> findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String name) {

        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if(!"".equals(name)){
                queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");
        return menuService.page(new Page<>(pageNum, pageSize),queryWrapper);
        }
        }

